'use strict'

/**
 * 封装公用的controllers方法
 */

var mongoose = require('mongoose');

const multer = require('koa-multer');//加载koa-multer模块  

const jwt = require('jwt-simple'); //解析token
const userModel = require("../models/user")
const config = require("config-lite")(__dirname);

//判断是否有参数
exports.hasBody = async (ctx, next) => {
    var body = ctx.request.body || {}
    // console.log(this.query.phonenumber)
    console.log(body)
  
    if (Object.keys(body).length === 0) {
		ctx.body = {
			code: "-1",
			message: '某参数缺失'
		}
		return next
    }
    await next()
}
//get请求，判断是否有params
exports.hasParams = async (ctx,next) => {
    var params = ctx.query || {}
    if (Object.keys(params).length === 0) {
        ctx.body = {
			code: "-1",
			message: '某参数缺失'
        }
        return next
	}
	await next()
}
//配置  
exports.storage = multer.diskStorage({  
    //文件保存路径  
    destination: function (req, file, cb) {  
      cb(null, 'public/uploads/')  
    },  
    //修改文件名称  
    filename: function (req, file, cb) {  
      var fileFormat = (file.originalname).split(".");  
      cb(null,Date.now() + "." + fileFormat[fileFormat.length - 1]);  
    }  
})  
/**
 * 验证token
 * @param {*} ctx 
 * @param {*} next 
 */
exports.verifyToken = async (ctx, next) => {
	var token = ctx.request.body.token || ctx.query.token
	
	if(token){
		var payload = jwt.decode(token, config.secret, 'HS256');
		if(payload.exp < new Date().getTime()){
			ctx.body = {
				code    : "-1",
				message : "token已过期"
			}
		}
		if(payload.uuid){
			var user = await userModel.findUser({uuid : payload.uuid});
			if(user.length <= 0){
				ctx.body = {
					code    : "-1",
					message : "token错误"
				}
			}
		}else{
			ctx.body = {
				code    : "-1",
				message : "token错误"
			}
		}
		await next()
	}else{
		ctx.body = {
			code    : "-1",
			message : "token不存在"
		}
	}
}